import './user.scss'
import { Button, Form, Input, DatePicker, Tooltip, message } from 'antd'
import { useState, useEffect, useRef } from 'react'
import { UserOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons'
import { useSelector, useDispatch } from 'react-redux'
import { reqUpdateUserInfo, reqUpdateUserImg } from '@/api/user'
import dayjs from 'dayjs'
import { UserActions } from '@/store'
import { baseURL } from '@/setting'

function User() {
  const [form] = Form.useForm()
  const dispatch: any = useDispatch()
  const fileInputRef = useRef<HTMLInputElement>(null)

  const userInfo = useSelector((state: any) => state.user.userInfo)
  const [formData, setFormData] = useState(userInfo)

  const handleValuesChange = (_: any, data: any) => {
    setFormData({ ...formData, ...data })
  }

  useEffect(() => {
    form.setFieldsValue({
      ...formData,
      birthday: formData.birthday ? dayjs(formData.birthday) : null,
    })
  }, [formData, form])

  // 用户个人数据修改
  const updateUserInfo = async () => {
    const res = await reqUpdateUserInfo(formData)
    if (res.code === 200) {
      dispatch(UserActions.getUserInfo())
      message.success('修改成功！')
    } else {
      message.error('修改失败！')
    }
  }

  const handleChangeImg = () => {
    fileInputRef.current!.click()
  }

  // 头像上传
  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const maxFileSize = 1 * 1024 * 1024
      if (file.size > maxFileSize) {
        message.warning('头像大小不能超过1MB！')
        return
      }
      // 只允许 JPG 文件
      const allowedExtensions = /(\.jpg|\.jpeg)$/i
      if (!allowedExtensions.exec(file.name)) {
        message.warning('只能上传 JPG 文件！')
        return
      }

      const formData = new FormData()
      formData.append('file', file)
      const res = await reqUpdateUserImg(formData)
      if (res.code === 200) {
        dispatch(UserActions.getUserInfo())
        message.success('上传成功！')
      } else {
        message.error('上传失败！')
      }
    }
  }

  useEffect(() => {
    if (userInfo.image) {
      setFormData(userInfo)
    }
  }, [userInfo])

  return (
    <div className="User">
      <div className="user-form">
        <div className="left">
          <Form
            form={form}
            name="basic"
            size="large"
            wrapperCol={{ span: 16 }}
            onValuesChange={handleValuesChange}
            autoComplete="off"
          >
            <Form.Item>
              <span style={{ fontWeight: '600', fontSize: '25px' }}>信息修改</span>
            </Form.Item>
            <Form.Item name="email">
              <Input prefix={<MailOutlined />} placeholder="请输入邮箱" disabled />
            </Form.Item>
            <Form.Item name="username">
              <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item name="phone">
              <Input prefix={<PhoneOutlined />} placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item name="birthday">
              <DatePicker />
            </Form.Item>
            <Form.Item>
              <Button onClick={updateUserInfo} className="btn" type="primary">
                修改
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className="right">
          <Tooltip title="修改头像" placement="right">
            <div className="right-img">
              <img
                onClick={handleChangeImg}
                src={
                  formData.image ? `${baseURL}/img/${formData.image}` : '/assets/images/avatar.png'
                }
                alt=""
              />
              <input
                type="file"
                style={{ display: 'none' }}
                onChange={handleFileChange}
                ref={fileInputRef}
              />
            </div>
          </Tooltip>
        </div>
      </div>
    </div>
  )
}

export default User
